package qeug.shsh.sso;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.lang.Lang;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.login.thirdauth.ThirdSSOAuthHandler;
import kd.bos.login.thirdauth.UserAuthResult;
import kd.bos.login.thirdauth.UserProperType;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.util.StringUtils;
import qeug.shsh.helper.SsoHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @projectName: qeug-cosmic-root-project
 * @package: qeug.shsh.sso
 * @className: ThirdSSOAuthHandler
 * @author: wenyx
 * @description: TODO
 * @date: 2023/10/13 9:33
 * @version: 1.0
 *
 */
public class SSOLoginPugin implements ThirdSSOAuthHandler {
    private static final Log log = LogFactory.getLog(SSOLoginPugin.class);
    @Override
    public void callTrdSSOLogin(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s) {
        log.info("回调地址"+s);
        String string = httpServletRequest.getRequestURL().toString();
        if(string.contains("mobile.html")){
            return;

        }
        StringBuffer loginUrl = new StringBuffer();
        SsoHelper ssoHelper = new SsoHelper();
        String sso_domain = ssoHelper.getSSO_DOMAIN();
        String client_id = ssoHelper.getClient_id();
        String client_secret = ssoHelper.getClient_secret();
        String back_url = ssoHelper.getBack_url();

        if (httpServletRequest.getRequestURI().contains("logout")){//当是退出时，重写定向到
            String logurl = sso_domain+"/logout";
            log.info("获取登出重定向URL：" + logurl);
            try {
                httpServletResponse.sendRedirect(logurl);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

//        if(httpServletRequest.getRequestURI().contains("download.do")){
//            return;
//        }

//        ${SSO_DOMAIN}/esc-sso/oauth2.0/authorize? client_id=XXXX&response_type=code&redirect_uri=http%3A%2F%2FXXXX.XXXX.XXXX.XXXX/XXX/XX
//        X%3A8080%2FXXXX%2FXXXX&oauth_timestamp=1489739502583&state=http%3A%2F%2Fwww.a
//        pp1.com%2Ftodu%2F1w2341123

        loginUrl.append(sso_domain);
        loginUrl.append("esc-sso/oauth2.0/authorize?");
        try {
            loginUrl.append("client_id="+client_id+"&response_type=code&redirect_uri="+URLEncoder.encode(back_url,"UTF-8"));
            loginUrl.append("&oauth_timestamp="+new Date().getTime());
            log.info("开始访问,地址为："+loginUrl);
            httpServletResponse.sendRedirect(loginUrl.toString());
        } catch ( IOException e) {
            e.printStackTrace();
            log.error(String.format("执行 callTrdSSOLogin(request,response,%s)异常：%s",s,e.getMessage()),e);
        }

    }


    @Override
    public UserAuthResult getTrdSSOAuth(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        SsoHelper ssoHelper = new SsoHelper();
        String string = httpServletRequest.getRequestURL().toString();
        if(string.contains("mobile.html")){
            return new UserAuthResult();
        }
        String sso_domain = ssoHelper.getSSO_DOMAIN();
        String client_id = ssoHelper.getClient_id();
        String client_secret = ssoHelper.getClient_secret();
        String back_url = ssoHelper.getBack_url();
        if (httpServletRequest.getRequestURI().contains("logout")){//当是退出时，重写定向到
            String logurl = sso_domain+"/logout";
            log.info("获取登出重定向URL：" + logurl);
            try {
                httpServletResponse.sendRedirect(logurl);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        String code = httpServletRequest.getParameter("code");
        if(StringUtils.isEmpty(code)){
            return new UserAuthResult();
        }
        log.info("接收到的账号："+code);


        //${SSO_DOMAIN}/esc-sso/oauth2.0/accessToken?
        //grant_type=authorization_code&oauth_timestamp=1489739169232&client_id=1001&client_secre
        //t=1001&code=b87576e1-fd14-47e5-a835-
        //0d601b18387a&redirect_uri=http%3A%2F%2FXX.XXX.XXX.XXX%3A8080%2FXXX%2FXXXX
        StringBuffer token_url = new StringBuffer();
        token_url.append(sso_domain);
        token_url.append("esc-sso/oauth2.0/accessToken?grant_type=authorization_code&oauth_timestamp="+new Date().getTime());
        try {
            token_url.append("&client_id="+client_id+"&client_secret="+client_secret+"&code="+code+"&redirect_uri="+URLEncoder.encode(back_url,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        log.info("拼接的获取token的URL："+token_url);
        String token = SsoHelper.getToken(token_url.toString());


        StringBuffer user_url = new StringBuffer();


        //${SSO_DOMAIN}/esc-sso/oauth2.0/profile?access_token=b1d508f3-32e7-4d6d-ac62-
        //87836406704c
        user_url.append(sso_domain);
        user_url.append("esc-sso/oauth2.0/profile?access_token="+token);
        log.info("拼接的获取user_id的URL："+token_url);
        String userId = SsoHelper.getUserId(user_url.toString());

//        String userId = "wc002";


        QFilter[] qFilters = new QFilter[]{
                new QFilter("number", QCP.equals,userId)
        };
        DynamicObject bos_user = BusinessDataServiceHelper.loadSingleFromCache("bos_user", "id", qFilters);

        UserAuthResult userAuthResult = new UserAuthResult();
        userAuthResult.setSucess(false);
        if(bos_user!=null&&bos_user.getLong("id")>0 ){
            userAuthResult.setUser(bos_user.getLong("id"));
            userAuthResult.setUserType(UserProperType.UserId);
            userAuthResult.setLangugage(Lang.zh_CN);
            userAuthResult.setSucess(true);
        }
        return userAuthResult;
    }

    @Override
    public boolean processLogoutLogic(HttpServletRequest servletRequest) {
        return ThirdSSOAuthHandler.super.processLogoutLogic(servletRequest);
    }
}
